package site.marqstree.latte.ec.main.index;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import site.marqstree.latte.ec.R;
import site.marqstree.latte.ui.recycler.RgbValue;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.ec.main.index
 * 文件名: TranslucentBehavior
 * 创建者: marqstree
 * 创建时间: 2020/1/27 13:57
 * 描述: TODO
 */
@SuppressWarnings("unused")
public class TranslucentBehavior extends CoordinatorLayout.Behavior<Toolbar> {

    //顶部距离
    private int mDistanceY = 0;
    //颜色变化速度
    private static final int SHOW_SPEED = 3;
    //定义变化的颜色
    private final RgbValue RGB_VALUE = RgbValue.create(255, 124, 2);

    //必须有两个参数的构造函数，否则报错
    public TranslucentBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //选择依赖控件为RecyclerView
    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, Toolbar child, View dependency) {
        //boolean bl = dependency.getId() == R.id.rv_index;
        boolean bl = dependency.getId() == R.id.srl_index;
        return bl;
    }

    @Override
    public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull Toolbar child, @NonNull View dependency) {
        return super.onDependentViewChanged(parent, child, dependency);
    }

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull Toolbar child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
        //return super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type);
        return true;
    }

    @Override
    public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull Toolbar child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
        //增加滑动距离
        mDistanceY += dy*0.6;
        //mDistanceY = Math.abs(mDistanceY);
        //toolbar的高度
        //final int targetHeight = child.getBottom();
        final int targetHeight = target.getBottom();

        //当滑动时，并且距离小于 toolbar 高度的时候，调整渐变色
        if (mDistanceY > 0 && mDistanceY <= targetHeight) {
            final double scale = mDistanceY*1.0 / targetHeight;
            final double alpha = scale * 255;
            child.setBackgroundColor(Color.argb((int) alpha, RGB_VALUE.getRed(), RGB_VALUE.getGreen(), RGB_VALUE.getBlue()));
        } else if (mDistanceY > targetHeight) {
            child.setBackgroundColor(Color.rgb(RGB_VALUE.getRed(), RGB_VALUE.getGreen(), RGB_VALUE.getBlue()));
        }
    }
}